package iNotes;

import iNotes.assist.DataPool;
import iNotes.assist.Utils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet(name = "DeleteItem", value = "/DeleteItem")
public class DeleteItem extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response){
        return;
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        if(!Utils.checkToken(session,request)){
            response.getWriter().write("CSRF attack detected!");
            return;
        }
        int noteID = Integer.parseInt(request.getParameter("id"));
        int uid = (int) session.getAttribute("uid");
        
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DataPool.ds.getConnection();
            if(Utils.checkBelonging(connection,uid,noteID)){
                preparedStatement = connection.prepareStatement("delete from user_note where note_id = ? and user_id = ?;");
                preparedStatement.setInt(1, noteID);
                preparedStatement.setInt(2,uid);
                preparedStatement.executeUpdate();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            Utils.close(connection,null,preparedStatement);
        }
        response.sendRedirect("notes.jsp");
    }
}
